<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2019/11/12
 * Time: 15:13
 */
namespace app\api\model;
use think\Controller;
use think\Model;
use think\Db;
use app\api\model\Hotel;
use app\common\model\OrderRefund as orf;
use app\api\model\OrderRefund as ore;
class Order extends Model
{
    /*
     * 我的订单
     */
    public function myOrder($uid,$type)
    {
        if($type==1){
            $where = '';
        }else if($type==2){
            $where['order_status'] = array('eq',0);
        }else if($type==3){
            $where['order_status'] = array('eq',1);
        }else if($type==4){
            $where['order_status'] = array('eq',3);
        }
        $tour = Db::name('tour_order')->alias('to')
            ->join('tours t','to.tour_id=t.tour_id','LEFT')
            ->join('tour_ticket tt','tt.tid=to.type_id','LEFT')
            ->field('to.order_id,to.tour_id as id,to.order_sn,to.ticket_date as time,to.create_time,to.order_status,to.pay_type,to.order_price,to.ticket_count,t.tour_name as title,tt.tname,tt.can_refund as is_quxiao,to.cancel_code,to.linkman,to.tel')
            ->where('to.user_id',$uid)
            ->where('to.is_del',0)
            ->where($where)
            ->select();
        foreach($tour as $k=>$v){
            $tour[$k]['type'] = 1;
            $tour[$k]['time'] = date('Y-m-d',$v['time']);
            $tour[$k]['room_name']='';
            $tour[$k]['room_amount']='';
            $tour[$k]['gtour_number']='';
            unset($tour[$k]['can_refund']);
        }

        $hotel = Db::name('hotel_order')->alias('ho')
            ->join('hotel h','ho.hotel_id=h.hotel_id','LEFT')
            ->join('hotel_room r','ho.room_id=r.room_id','left')
            ->field('ho.order_id,ho.order_sn,ho.cancel_code,ho.hotel_id as id,ho.room_name,ho.pay_type,ho.create_time,ho.room_amount,ho.order_price,ho.order_status,ho.start_time,ho.end_time,h.hotel_name as title,r.is_quxiao,ho.linkman,ho.tel')
            ->where('ho.uid',$uid)
            ->where('ho.is_del',0)
            ->where($where)
            ->select();
        foreach ($hotel as $k=>$v)
        {
            $hotel[$k]['type'] = 2;
            $hotel[$k]['time'] = date('Y-m-d',$v['start_time']).'至'.date('Y-m-d',$v['end_time']);
            $hotel[$k]['ticket_count'] = '';
            $hotel[$k]['tname'] = '';
            $hotel[$k]['gtour_number']='';
            unset($hotel[$k]['start_time']);
            unset($hotel[$k]['end_time']);
        }

        $team = Db::name('gtour_order')->alias('go')
            ->join('group_tour gt','go.gtour_id=gt.id','LEFT')
            ->field('go.order_id,go.order_sn,go.cancel_code,go.gtour_id as id,go.gtour_number,go.create_time,go.pay_type,go.gtour_start as time,go.order_price,go.order_status,gt.gtour_title as title,gt.is_quxiao,go.linkman,go.tel')
            ->where('go.user_id',$uid)
            ->where('go.is_del',0)
            ->where($where)
            ->select();
        foreach ($team as $k=>$v){
            $team[$k]['type'] = 3;
            $team[$k]['time'] = date('Y-m-d',$v['time']);
            $team[$k]['ticket_count'] = '';
            $team[$k]['tname'] = '';
            $team[$k]['room_name']='';
            $team[$k]['room_amount']='';
            $team[$k]['is_quxiao'] = '1';

        }


        $c = array_merge($tour,$hotel,$team);
        if(!empty($c)){
            $last_names = array_column($c,'create_time');
            array_multisort($last_names,SORT_DESC,$c);
        }
        return $c;
    }
      
  
   /**
     * [getOrderInfo 获取订单信息]
     * @Author   kendy
     * @DateTime 2019-12-20T10:01:43+0800
     * @param    [type]                   $where [description]
     * @return   [type]                          [description]
     */
    public function getOrderInfo($type,$where)
    { 
              $res = [];
              //修改订单状态
            if($type==1){ 
                $res = Db::name('tour_order')
                ->alias('o')
                ->field('o.tour_id as shop_id,o.user_id as uid,o.order_status,o.pay_type,o.order_id,t.sale_sum,o.order_sn,o.order_price,o.type_id')
                ->join('tours t','o.tour_id=t.tour_id','left')  
                ->where($where)
                ->find();
                 return $res;
            }
            if($type==2){ 
                 $res = Db::name('hotel_order')
                ->alias('o')
                ->field('o.hotel_id as shop_id,send_tel,h.hotel_name,tel,o.uid,o.pay_type,o.order_status,o.room_id,o.order_id,h.sum_sale,o.order_sn,o.order_price')
                ->join('hotel h','o.hotel_id=h.hotel_id','left')  
                ->where($where)
                ->find(); 
                return $res;
            }
            if($type==3){
                $res = Db::name('gtour_order')
                ->alias('o')
                ->field('o.team_id as shop_id,o.gtour_id,o.user_id as uid,o.pay_type,o.order_id,gt.sale_sum,gt.id,o.order_sn,o.order_price')
                ->join('group_tour gt','o.gtour_id=gt.id','left')
                ->where($where)
                ->find();
               return $res;
            } 
         return $res;
       
    }

    public function cancelOrder()
    { 
            $orderId = (int)input('post.order_id');  
            $type = (int)input('post.type');  
            if(empty($orderId)) 
             return apiReturn('400','订单id为空',0);       
            $userId = input('post.uid');
            if(empty($userId)) 
             return apiReturn('400','用户信息为空',0); 
             if(empty($type)) 
             return apiReturn('400','订单类型为空',0);   
            $where['o.is_del'] = 0;
            $where['order_id'] = $orderId;
            $where['order_status'] = ['IN',[1,6]];
            if($type==1){ 
              $where['user_id'] = $userId;
            }
            if($type==2) 
            $where['uid'] = $userId;   
            $orderInfo =  $this->getOrderInfo($type,$where);    
            if(!empty($orderInfo)){
                   Db::startTrans();
                   try{
                    $orf = new orf();
                    $data['order_status'] = 5;
                    $data['cancel_id'] = 1;
                    $data['is_refund'] = 1;
                     //查看退款订单是否存在
                    $is_refund = Db::name('order_refund')
                    ->where('order_sn',$orderInfo['order_sn'])
                    ->find();
                    if(!empty($is_refund)){ 
                      
                         if($is_refund['refund_status'] == 0){ 
                            return apiReturn('400','请勿重复申请退款',0); 
                         }elseif($is_refund['refund_status'] == 2){ 
                            return apiReturn('400','商家已拒绝，请勿重复取消',0); 
                        } 

                    }
                    //退款订单记录表参数
                    $obj['order_sn'] = $orderInfo['order_sn'];
                    $obj['order_price'] = $orderInfo['order_price']; 
                    $obj['user_id'] = $orderInfo['uid'];
                    $obj['object_id'] = $orderInfo['shop_id'];
                     //商品销量减一,修改订单的状态
                      if($type==1){ // 景点 
                         $obj['refund_reason'] = "景点用户申请退款";  
                         $obj['object_type'] = 2;
                         $orderInfo['refund_reason'] = "景点用户申请退款"; 
                            $payType = $orderInfo['pay_type'];//1支付宝 2微信   
                            if($payType == 1){
                               $rs = $orf->aliRefund($orderInfo);
                            }
                            if($payType == 2){  
                                $rs = $orf->weixinRefund($orderInfo);
                            }
                            if($rs == 'SUCCESS'){
                                $obj['refund_status'] = 1; 
                                    Db::name('tours')
                                    ->where('tour_id',$orderInfo['shop_id'])
                                    ->setDec('sale_sum',1);  
                                     Db::name('tour_order')
                                    ->where('order_id',$orderInfo['order_id'])
                                    ->update($data); 
                            }else{ 
                             return apiReturn('400','退款失败',0); 
                            } 
                     }
                     elseif($type==2){ //酒店
                        //查看该酒店订单的房间类型是否可退
                        $roomInfo = Db::name('hotel_room')
                        ->where('room_id',$orderInfo['room_id'])
                        ->find();
                        if($roomInfo['is_quxiao'] !== 1){
                          return apiReturn('400','该酒店房间类型不可取消',0); 
                        }
                        if($roomInfo['is_quxiao'] == 1){  
                            if(strtotime(date('Y-m-d ').$roomInfo['cancelable_time']) <   time())
                            {
                              return apiReturn('400','当前已过可取消时间',0); 
                            }


                        }
                         $obj['refund_reason'] = "酒店用户申请退款";  
                         $obj['object_type'] = 4; 
                         
                        //查看该订单状态是否是待确认6，6,直接退款
                        if($orderInfo['order_status'] == 6){
                           $orderInfo['refund_reason'] = "酒店用户申请退款"; 
                            $payType = $orderInfo['pay_type'];//1支付宝 2微信   
                            if($payType == 1){
                               $rs = $orf->aliRefund($orderInfo);
                            }
                            if($payType == 2){  
                                $rs = $orf->weixinRefund($orderInfo);
                            }
                            if($rs == 'SUCCESS'){
                                $obj['refund_status'] = 1;   
                                Db::name('hotel')
                                ->where('hotel_id',$orderInfo['shop_id'])
                                ->setDec('sum_sale',1);
                                Db::name('hotel_order')
                                ->where('order_id',$orderInfo['order_id'])
                                ->update($data); 
                                //发送给商户信息
                                 $sendData = [
                                    '1'=>$orderInfo['hotel_name'],
                                    '2'=> $orderInfo['order_sn']
                                ];  
                              sendJsmsMessage($orderInfo['send_tel'],174984,$sendData);
                                //发送给用户退款信息 
                                  $sends = [
                                    '1'=>$orderInfo['order_sn'],
                                    '2'=> $orderInfo['order_price']
                                ];  
                              sendJsmsMessage($orderInfo['tel'],174983,$sends);
                            }else{ 
                             return apiReturn('400','退款失败',0); 
                            } 
                        } 
                        if($orderInfo['order_status'] == 1){ 
                            $obj['refund_status'] = 0;
                             //新增订单日志
                             $logOrder['order_id'] = $orderInfo['order_id'];
                             $logOrder['order_status'] = 5;
                             $logOrder['log_content'] = "用户取消订单";
                             $logOrder['user_id'] = $userId;
                             $logOrder['create_time'] = time();
                             $logOrder['order_type'] = $type;
                             Db::name('log_orders')->insert($logOrder);  
                             //记录到退款记录表  
                             $orderRefund = new ore(); 
                             $orderRefund->addOrderRefund($obj);   
                             return apiReturn('200','订单取消成功,请耐心等待商户审核',0);   
                        }
                     }
                     elseif($type==3){
                         // 跟团 
                         $obj['refund_reason'] = "跟团用户申请退款";  
                         $obj['object_type'] = 3;
                         $orderInfo['refund_reason'] = "跟团用户申请退款"; 
                            $payType = $orderInfo['pay_type'];//1支付宝 2微信   
                            if($payType == 1){
                               $rs = $orf->aliRefund($orderInfo);
                            }
                            if($payType == 2){  
                                $rs = $orf->weixinRefund($orderInfo);
                            }
                            if($rs == 'SUCCESS'){
                                $obj['refund_status'] = 1; 
                                    Db::name('group_tour')
                                    ->where('id',$orderInfo['gtour_id'])
                                    ->setDec('sale_sum',1); 
                                     Db::name('gtour_order')
                                    ->where('order_id',$orderInfo['order_id'])
                                    ->update($data); 
                            }else{ 
                             return apiReturn('400','退款失败',0); 
                            }  
                        
                     } 
                     //新增订单日志
                     $logOrder['order_id'] = $orderInfo['order_id'];
                     $logOrder['order_status'] = 5;
                     $logOrder['log_content'] = "用户取消订单";
                     $logOrder['user_id'] = $userId;
                     $logOrder['create_time'] = time();
                     $logOrder['order_type'] = $type;
                     Db::name('log_orders')->insert($logOrder);  
                     //记录到退款记录表  
                     $orderRefund = new ore(); 
                     $orderRefund->addOrderRefund($obj);        
                     Db::commit(); 
                     return apiReturn('200','订单取消成功',0);       
                   }catch(\Exception $e){  
                      Db::rollback();    
                      return apiReturn('400',$e->getMessage(),0);  
                   }
                  
                }
                return apiReturn('400','订单取消失败',0);   
    }









               
 


}
